/**
 * Edge浏览器专用修复工具
 * 解决Edge在IP地址访问时的特殊问题
 */

interface BrowserInfo {
  isEdge: boolean;
  isChrome: boolean;
  userAgent: string;
  version?: string;
}

class EdgeBrowserFix {
  private static instance: EdgeBrowserFix;
  private browserInfo: BrowserInfo;

  static getInstance(): EdgeBrowserFix {
    if (!EdgeBrowserFix.instance) {
      EdgeBrowserFix.instance = new EdgeBrowserFix();
    }
    return EdgeBrowserFix.instance;
  }

  constructor() {
    this.browserInfo = this.detectBrowser();
    this.applyEdgeFixes();
  }

  /**
   * 检测浏览器类型
   */
  private detectBrowser(): BrowserInfo {
    const userAgent = navigator.userAgent;
    
    const isEdge = /Edge\//.test(userAgent) || /Edg\//.test(userAgent);
    const isChrome = /Chrome\//.test(userAgent) && !isEdge;
    
    let version;
    if (isEdge) {
      const match = userAgent.match(/Edg?\/(\d+)/);
      version = match ? match[1] : undefined;
    }

    // console.log('🔍 浏览器检测结果:', {
    //   isEdge,
    //   isChrome,
    //   userAgent,
    //   version
    // });

    return { isEdge, isChrome, userAgent, version };
  }

  /**
   * 应用Edge专用修复
   */
  private applyEdgeFixes(): void {
    if (!this.browserInfo.isEdge) {
      return;
    }

    // console.log('🔧 检测到Edge浏览器，应用专用修复');

    // 1. 清除可能的缓存问题
    this.clearEdgeCache();

    // 2. 添加请求拦截器
    this.setupRequestInterceptor();

    // 3. 处理网络环境特殊情况
    this.handleNetworkEnvironment();

    // 4. 设置Edge专用的全局配置
    this.setupEdgeGlobalConfig();
  }

  /**
   * 清除Edge特有的缓存问题
   */
  private clearEdgeCache(): void {
    try {
      // 清除Edge可能缓存的失败请求
      if ('caches' in window) {
        caches.keys().then(cacheNames => {
          cacheNames.forEach(cacheName => {
            if (cacheName.includes('api') || cacheName.includes('network')) {
              caches.delete(cacheName);
              // console.log('🗑️ 清除Edge API缓存:', cacheName);
            }
          });
        });
      }

      // 清除可能的DNS缓存标记
      sessionStorage.removeItem('edge_dns_cache');
      sessionStorage.removeItem('edge_api_failure');

    } catch (error) {
      // console.warn('⚠️ Edge缓存清理失败:', error);
      console.error('Edge cache cleaning failed', error);
    }
  }

  /**
   * 设置请求拦截器，处理Edge的特殊情况
   */
  private setupRequestInterceptor(): void {
    const originalFetch = window.fetch;

    window.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
      const url = typeof input === 'string' ? input : input.toString();
      
      // Edge在IP访问时的特殊处理
      if (this.isNetworkAccess() && url.includes('127.0.0.1')) {
        // console.log('🔧 Edge: 检测到IP访问环境下的127.0.0.1请求，进行地址转换');
        
        const newUrl = url.replace('127.0.0.1', window.location.hostname);
        // console.log('🔧 Edge: 地址转换:', url, '→', newUrl);
        
        // 修改请求URL
        const newInput = typeof input === 'string' ? newUrl : new URL(newUrl);
        
        // Edge需要明确的CORS设置
        const newInit = {
          ...init,
          mode: 'cors' as RequestMode,
          credentials: 'omit' as RequestCredentials,
          headers: {
            ...init?.headers,
            'Cache-Control': 'no-cache',
            'Pragma': 'no-cache'
          }
        };

        return originalFetch(newInput, newInit);
      }

      // 对于Edge，添加额外的缓存控制
      if (init) {
        init.headers = {
          ...init.headers,
          'Cache-Control': 'no-cache',
          'Pragma': 'no-cache'
        };
      }

      return originalFetch(input, init);
    };
  }

  /**
   * 处理网络环境的特殊情况
   */
  private handleNetworkEnvironment(): void {
    if (!this.isNetworkAccess()) {
      return;
    }

    // console.log('🌐 Edge: 网络环境特殊处理');

    // Edge在网络环境下可能需要预热DNS
    this.preloadDNS();

    // 设置网络环境标记
    sessionStorage.setItem('edge_network_mode', 'true');
    sessionStorage.setItem('edge_api_base', `${window.location.protocol}//${window.location.hostname}:8000`);
  }

  /**
   * 预加载DNS，解决Edge的网络延迟问题
   */
  private preloadDNS(): void {
    const hostname = window.location.hostname;
    const apiUrl = `${window.location.protocol}//${hostname}:8000`;

    // 创建隐藏的链接元素进行DNS预加载
    const link = document.createElement('link');
    link.rel = 'dns-prefetch';
    link.href = apiUrl;
    document.head.appendChild(link);

    // 预热连接
    const linkPreload = document.createElement('link');
    linkPreload.rel = 'preconnect';
    linkPreload.href = apiUrl;
    document.head.appendChild(linkPreload);

    // console.log('🔧 Edge: DNS预加载完成:', apiUrl);
  }

  /**
   * 设置Edge专用的全局配置
   */
  private setupEdgeGlobalConfig(): void {
    // 设置Edge专用的全局变量
    (window as any).EDGE_BROWSER_MODE = true;
    (window as any).EDGE_API_CONFIG = {
      isNetworkAccess: this.isNetworkAccess(),
      apiBase: this.isNetworkAccess() 
        ? `${window.location.protocol}//${window.location.hostname}:8000`
        : 'http://127.0.0.1:8000'
    };

    // console.log('🔧 Edge全局配置:', (window as any).EDGE_API_CONFIG);
  }

  /**
   * 检查是否为网络访问
   */
  private isNetworkAccess(): boolean {
    const hostname = window.location.hostname;
    return hostname !== 'localhost' && hostname !== '127.0.0.1';
  }

  /**
   * 获取Edge专用的API地址
   */
  getApiUrl(): string {
    if (this.isNetworkAccess()) {
      return `${window.location.protocol}//${window.location.hostname}:8000`;
    }
    return 'http://127.0.0.1:8000';
  }

  /**
   * Edge专用的错误恢复
   */
  handleEdgeError(error: any, url: string): void {
    if (!this.browserInfo.isEdge) {
      return;
    }

    // console.log('🔧 Edge错误处理:', error, url);

    // 记录Edge特有的错误
    sessionStorage.setItem('edge_last_error', JSON.stringify({
      error: error.message || error.toString(),
      url,
      timestamp: Date.now()
    }));

    // 如果是网络错误，尝试重置网络状态
    if (error.message?.includes('Failed to fetch') || error.message?.includes('NetworkError')) {
      this.resetNetworkState();
    }
  }

  /**
   * 重置网络状态
   */
  private resetNetworkState(): void {
    // console.log('🔧 Edge: 重置网络状态');
    
    // 清除网络相关的缓存
    sessionStorage.removeItem('edge_dns_cache');
    sessionStorage.removeItem('edge_api_failure');
    
    // 重新进行DNS预加载
    setTimeout(() => {
      this.preloadDNS();
    }, 1000);
  }

  /**
   * 获取Edge诊断信息
   */
  getDiagnostics(): any {
    const lastError = sessionStorage.getItem('edge_last_error');
    
    return {
      browserInfo: this.browserInfo,
      isNetworkAccess: this.isNetworkAccess(),
      apiUrl: this.getApiUrl(),
      lastError: lastError ? JSON.parse(lastError) : null,
      networkMode: sessionStorage.getItem('edge_network_mode'),
      timestamp: Date.now()
    };
  }
}

// 导出单例
export const edgeBrowserFix = EdgeBrowserFix.getInstance();

// 开发环境调试工具
if (import.meta.env.DEV) {
  (window as any).edgeDebug = {
    fix: edgeBrowserFix,
    getDiagnostics: () => edgeBrowserFix.getDiagnostics(),
    getApiUrl: () => edgeBrowserFix.getApiUrl(),
    resetNetwork: () => edgeBrowserFix['resetNetworkState']()
  };
} 